<?php

/**
 * Menashop
 *
 * LICENSE
 *
 * This source file is subject to the license that is bundled
 * with this project in the file LICENSE.txt
 *
 * @category   Zend
 * @package    AuthController
 * @copyright  Copyright (c) 2011 Menashop UA Inc. (http://www.menashop.com.ua)
 * @license    LICENSE.txt
 * @version    1.0.0
 * @since      File available since Release 1.0.0
 */

/**
 * @category   Zend
 * @package    AuthController
 * @copyright  Copyright (c) 2011 Menashop UA Inc. (http://www.menashop.com.ua)
 * @license    LICENSE.txt
 */
class Admin_AuthController extends Zend_Controller_Action
{

    /**
     * The logger
     * @var Zend_Log
     */
    protected $_logger;

    /**
     * The auth data
     * @var Zend_Auth
     */
    protected $_auth;

    /**
     * Initialize the controller
     */
    public function init()
    {
        // Get logger
        $this->_logger = Zend_Registry::get('log');

        // Set admin layout
        $this->_helper->layout()->setLayout('admin');

        // Get auth data
        $this->_auth = Zend_Auth::getInstance();

        // Get language from locale
        $locale = Zend_Registry::get('Zend_Locale');
        $this->view->language = $locale->getLanguage();

        // Get current url without language
        $this->view->currentUrl = str_replace('/' . $locale->getLanguage(), '', $this->_request->getRequestUri());

        $this->view->shopName = Zend_Registry::get('config')->shopName;
    }

    /**
     * Action for login
     */
    public function loginAction()
    {
        $form = new Admin_Model_FormLogin();
        $form->setAction('/' . $this->view->language . '/admin/login');

        // Has the login form been posted?
        if ($this->getRequest()->isPost()) {

            // If the submitted data is valid, attempt to authenticate the user
            if ($form->isValid($this->_request->getPost())) {

                // Did the user successfully login?
                if ($this->_authenticate($this->_request->getPost())) {
                    $this->_redirect('/' . $this->view->language . '/admin');
                } else {
                    sleep(3);
                    $this->_logger->err("Incorrect attempt to login from " . $this->_request->getServer('REMOTE_ADDR'));
                    $this->view->errors = $this->view->translate('Login failed, please try again');
                }
            } else {
                $this->view->errors = $form->getErrors();
            }
        }
        $this->view->formLogin = $form;

        // Get time of execution
        $startTime = Zend_Registry::get('startTime');
        $totalTime = round(microtime(true) - $startTime, 3);
        $this->_logger->debug(__METHOD__." spent $totalTime s");
    }

    /**
     * Action for logout
     */
    public function logoutAction()
    {
        $this->_auth->clearIdentity();
        $this->_redirect('/' . $this->view->language . '/admin/login');
    }

    /**
     * Authentication of user
     * @param array $data
     *      Data from login form
     * @return boolean
     */
    protected function _authenticate($data)
    {
        // Initialize auth adapter
        $db = Zend_Db_Table::getDefaultAdapter();
        $authAdapter = new Zend_Auth_Adapter_DbTable($db);
        $authAdapter->setTableName('user');
        $authAdapter->setIdentityColumn('email');
        $authAdapter->setCredentialColumn('password');
        $authAdapter->setCredentialTreatment('MD5(CONCAT(?,salt))');
        $authAdapter->setIdentity($data['email']);
        $authAdapter->setCredential($data['password']);

        // Check auth data
        $result = $this->_auth->authenticate($authAdapter);
        return $result->isValid();
    }

}

